package com.boby.homecamera

import android.os.Bundle
import android.util.Log
import android.view.Surface
import android.view.TextureView
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.pedro.common.ConnectChecker
import com.pedro.encoder.input.video.CameraHelper
import com.pedro.encoder.input.video.CameraOpenException
import com.pedro.library.view.GlStreamInterface
import com.pedro.rtspserver.RtspServerCamera2
import com.pedro.rtspserver.server.ClientListener
import com.pedro.rtspserver.server.ServerClient

class Camera2Activity : AppCompatActivity() {
    private lateinit var rtspServerCamera2: RtspServerCamera2
    private lateinit var connectChecker:ConnectChecker
    private lateinit var bt_startServer:Button
    private lateinit var bt_switchCamera:Button
    private lateinit var bt_startPreview:Button
    private lateinit var ttv_preview:TextureView
    private lateinit var tv_url:TextView
    private val TAG = "Camera2Activity"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camera2)
        bt_startServer = findViewById(R.id.bt_startServer)
        bt_switchCamera = findViewById(R.id.bt_switchCamera)
        bt_startPreview = findViewById(R.id.bt_startPreview)
        ttv_preview = findViewById(R.id.ttv_preview)
        tv_url = findViewById(R.id.tv_url)
        initRtsp()
    }

    private fun initRtsp(){
        connectChecker = object:ConnectChecker{
            override fun onAuthError() {
                Log.d(TAG,"onAuthError")
//                rtspServerCamera1.stopStream()
            }

            override fun onAuthSuccess() {
                Log.d(TAG,"onAuthSuccess")
            }

            override fun onConnectionFailed(reason: String) {
                Log.d(TAG,"onConnectionFailed $reason")
//                rtspServerCamera1.stopStream()
            }

            override fun onConnectionStarted(url: String) {
                Log.d(TAG,"onConnectionStarted :$url ")
            }

            override fun onConnectionSuccess() {
                Log.d(TAG,"onConnectionSuccess")
            }

            override fun onDisconnect() {
                Log.d(TAG,"onDisconnect")
            }

        }
        rtspServerCamera2 =  RtspServerCamera2(this,connectChecker,1935)

        rtspServerCamera2.streamClient.setClientListener(object : ClientListener{
            override fun onClientConnected(client: ServerClient) {
                Log.d(TAG,"onClientConnected ${client.getAddress()}")
                client.setLogs(false)
            }

            override fun onClientDisconnected(client: ServerClient) {
                Log.d(TAG,"onClientDisconnected ${client.getAddress()}")
            }

            override fun onClientNewBitrate(bitrate: Long, client: ServerClient) {
//                Log.d(TAG,"onClientNewBitrate bitrate:bitrate ,${client.getAddress()}")
            }

        })

        bt_startServer.setOnClickListener {
            if(rtspServerCamera2.isStreaming){
                stopRtspServer()
                bt_startServer.text = "Start Server"
            }else{
                startRtspServer()
                bt_startServer.text = "Stop Server"
            }
        }

        bt_switchCamera.setOnClickListener {
            try {
                rtspServerCamera2.switchCamera()
            } catch (e: CameraOpenException) {
                Toast.makeText(this, e.message, Toast.LENGTH_SHORT).show()
            }
        }
        var isDetachPreView = false

        bt_startPreview.setOnClickListener {
           val glInterface =  rtspServerCamera2.glInterface
            if(glInterface is GlStreamInterface){
                if(isDetachPreView){
                    glInterface.deAttachPreview()
//                    glInterface.takePhoto(null)
                    isDetachPreView = false
                    bt_startPreview.text = "Start PreView"
                }else{
                    glInterface.attachPreview(Surface(ttv_preview.surfaceTexture))
                    isDetachPreView = true
                    bt_startPreview.text = "Stop PreView"

                }


            }

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        destroyRtsp()
    }

    private fun startRtspServer(){
        if(rtspServerCamera2.isRecording || prepare()){
            rtspServerCamera2.startStream()
            tv_url.text = rtspServerCamera2.streamClient.getEndPointConnection()
        }

    }
    private fun stopRtspServer(){

    }
    val cameraWidth = 1920
    val cameraHeight = 1080
    private fun prepare(): Boolean {
        val rotation = CameraHelper.getCameraOrientation(this)
        val prepared = rtspServerCamera2.prepareAudio() && rtspServerCamera2.prepareVideo(cameraWidth, cameraHeight, 30, cameraWidth * cameraHeight * 2, rotation)
//        adaptPreview()
        return prepared
    }

    private fun destroyRtsp(){
        if ( rtspServerCamera2.isRecording) {
            rtspServerCamera2.stopRecord()
        }
        if (rtspServerCamera2.isStreaming) {
            rtspServerCamera2.stopStream()

        }
        if (rtspServerCamera2.isOnPreview) rtspServerCamera2.stopPreview()

    }
}